package com.yan.mvc.config;

import com.yan.crowd.entity.Admin;
import com.yan.crowd.entity.Role;
import com.yan.service.AdminService;
import com.yan.service.AuthService;
import com.yan.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CrowdDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据账号名称查询admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);

        // 获取admin-id
        Integer id = admin.getId();

        // 根据adminId来查询角色信息
        List<Role> assignedRole = roleService.getAssignedRole(id);

        // 根据adminId查询权限信息
        List<String> assignedAuthNameByAdminId = authService.getAssignedAuthNameByAdminId(id);

        // 创建集合对象来存储GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();

        assignedRole.stream().map(item->{
            String roleName = "ROLE_" + item.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
            return simpleGrantedAuthority;
        });

        assignedAuthNameByAdminId.stream().map(item->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item);
            authorities.add(simpleGrantedAuthority);
            return simpleGrantedAuthority;
        });

        // 封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        // 返回
        return securityAdmin;
    }

}
